<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" v-show="showSearch" :inline="true">
      <el-form-item label="排班名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入排班名称"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="状态"
          clearable
          size="small"
          style="width: 240px"
        >
          <el-option
            v-for="dict in statusOptions"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="保存时间">
        <el-date-picker
          v-model="dateRange"
          size="small"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>

      <el-form-item label="创建人" prop="createBy">
        <el-input
          v-model="queryParams.createBy"
          placeholder="请输入创建人名称"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['job:termSchedule:add']"
        >新增
        </el-button>
        <el-button
          type="primary"
          plain
          icon="el-icon-delete"
          size="mini"
          @click="handleDelete"
          v-hasPermi="['job:termSchedule:del']"
        >删除
        </el-button>
        <el-button
          type="primary"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['job:termSchedule:export']"
        >导出</el-button>
        <el-button
          plain
          type="primary"
          icon="el-icon-edit"
          size="mini"
          v-hasPermi="['job:termSchedule:config']"
          @click="openCycleConfig">
          周期设置</el-button>
      </el-col>



      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table v-loading="loading" :data="termScheduleList" @selection-change="handleSelectionChange">
      <el-table-column
        type="selection"
        width="55">
      </el-table-column>
      <el-table-column label="序号" type="index" align="center">
        <template slot-scope="scope">
          <span>{{(pageNum - 1) * pageSize + scope.$index + 1}}</span>
        </template>
      </el-table-column>
      <el-table-column label="排班表名称" prop="name" :show-overflow-tooltip="true" width="100"/>
      <el-table-column label="人数" prop="userNum"  width="150"/>
      <el-table-column label="创建人" prop="createBy" :show-overflow-tooltip="true" width="120"/>
      <el-table-column label="保存时间" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" width="100">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="0"
            :inactive-value="1"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>


      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['job:termSchedule:edit']"
          >编辑
          </el-button>

          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['job:termSchedule:del']"
          >删除
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
            v-hasPermi="['job:termSchedule:view']"
          >详情
          </el-button>

        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改班次对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="880px" append-to-body>
      <el-form ref="form" :model="form"  :rules="rules" label-width="80px">
        <span style="font-weight:bold">基本信息</span>
        <el-divider></el-divider>
        <el-row>
          <el-col :span="12">
            <el-form-item label="排班名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入排班名称"   style="width: 180px"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="考勤组" prop="groupId">
              <el-select
                v-model="form.groupId"
                placeholder="考勤组"
                clearable
                size="small"
                style="width: 240px"
                :disabled="disabledValue"
              >
                <el-option
                  v-for="dict in groupOptions"
                  :key="dict.roleId"
                  :label="dict.roleName"
                  :value="dict.roleId"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>

          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select
                v-model="form.status"
                placeholder="状态"
                clearable
                size="small"
                style="width: 240px"
                :disabled="disabledValue"
              >
                <el-option
                  v-for="dict in statusOptions"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <span>
         <span style="font-weight:bold">排班信息</span>

        </span>

        <el-divider></el-divider>

       <span>
         班次说明：
          <el-row style="margin-top: 15px" v-for="(item,index) in termTimeShifList " :key="index">

          <span   style="display:block;float:left;width:400px;height:40px;line-height:30px; border:2px;border-style:solid;background:#32CD32">{{item.showDateTime}}</span>

        </el-row>
        <el-row style="margin-top: 15px" >
<!--          <el-col :span="8">-->
<!--            <span   style="display:block;float:left;width:120px;height:40px;line-height:30px;border:2px;border-style:solid; background:#A9A9A9; ">休息</span>-->
<!--          </el-col>-->
          <el-col :span="6">
            <span   style="display:block;float:left;width:120px;height:40px;line-height:30px;border:2px ;border-style:solid ;background:#FFFFFF ;">清空</span>
          </el-col>
        </el-row>
       </span>

        <span>
           <el-row style="margin-top: 15px" >
             <span>周期说明：</span>
              <el-button size="small" type="info" @click="openCycleConfig">周期设置</el-button>
           </el-row>

          <el-row style="margin-top: 15px" v-for="(item,index) in cycleScheduleList " :key="index">
          <el-col :span="12">
          <span width="60px" style="display:block;float:left;width:100px;height:40px;line-height:30px;border:2px;border-style:solid;background:#32CD32">{{item.name}}</span>
          </el-col>
        </el-row>
       </span>
        <el-row>
          <el-form-item label="排班时间" name="scheduleDate">
            <el-date-picker
              v-model="scheduleDateRange"
              size="small"
              style="width: 240px"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @change="changeDate"
              :disabled="disabledValue"
            ></el-date-picker>
          </el-form-item>
        </el-row>

        <el-row>
          使用方法：
        </el-row>
        <el-row>
         1、在人员的排班区域点击色块可以进行相应班次的填充，支持设置好排班周期后按周期填充。
        </el-row>
        <el-row>
          2、最大支持一次性按30天排班。
        </el-row>

        <el-divider></el-divider>
   <el-row>
    <el-col :span="9">
    <el-form-item label="岗位" prop="postName">
      <el-input
        v-model="queryInParams.postName"
        placeholder="请输入岗位"
        clearable
        size="small"
        style="width: 180px"

      />
    </el-form-item>
    </el-col>
    <el-col :span="8">
    <el-form-item label="用户名称" prop="userName">
      <el-input
        v-model="queryInParams.userName"
        placeholder="请输入用户名称"
        clearable
        size="small"
        style="width: 180px"
      />
    </el-form-item>


    </el-col>
     <el-col :span="6">
     <el-form-item>
       <el-button type="primary" icon="el-icon-search" size="mini" @click="handleTableQuery">搜索</el-button>

     </el-form-item>
     </el-col>
  </el-row>
        <el-row>
          <el-button icon="el-icon-refresh" size="mini" @click="resetTable">重置</el-button>
          <el-button icon="el-icon-import" size="mini" @click="handleImport">导入排班</el-button>
          <el-button icon="el-icon-import" size="mini" @click="handleTamplantExport">下载模板</el-button>

        </el-row>
        <el-table
          :data="tableData"
          border
          v-loading="userloading"
          style="width: auto"
          @cell-click="cellClick"
          :cell-class-name="tableCellClassName"
        >

          <el-table-column
            prop="userName"
            label="姓名"
            width="100px"
            fixed

          >
            <template slot-scope="scope">
            <span
              :style="{ color: (scope.row.userId == userId  || (scope.row.postId == postId && scope.row.postId !=''))  ? 'red' : '' }"
            >
              {{ scope.row.userName }}</span
            >
            </template>
          </el-table-column>
          <el-table-column
            prop="idCard"
            label="身份证"
            width="180px"
            fixed

          >
            <template slot-scope="scope">
            <span
              :style="{ color: (scope.row.userId == userId  || (scope.row.postId == postId && scope.row.postId !=''))  ? 'red' : '' }"
            >
              {{ scope.row.idCard }}</span
            >
            </template>
          </el-table-column>

          <el-table-column
            prop="postName"
            label="岗位"
            width="100px"
            fixed

          >
            <template slot-scope="scope">
            <span
              :style="{ color: (scope.row.userId == userId  || (scope.row.postId == postId && scope.row.postId !=''))  ? 'red' : '' }"
            >
              {{ scope.row.postName }}</span
            >
            </template>
          </el-table-column>

          <template v-for="(item,index)  in tableTitleData">
            <el-table-column
              :prop="item.value"
              :label="item.lable"
              width="90px"
            >
              <template slot-scope="scope">
            <span
              :style="{ color: (scope.row.userId == userId  || (scope.row.postId == postId && scope.row.postId !=''))  ? 'red' : '' }"
            >
              {{ scope.row[item.value]}}</span
            >
              </template>
            </el-table-column>
          </template>

        </el-table>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">保 存</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <el-dialog title="选择填充班次" :visible.sync="openSchedule" width="480px" append-to-body>

      <el-row>
        <el-tag type="info" :color="color1" @click="changTag(1)">单次填充</el-tag>
        <el-tag type="info" :color="color2" @click="changTag(2)">周期填充</el-tag>

      </el-row>
      <el-divider></el-divider>

      <el-row style="margin-top: 15px" >

<!--          <span   style="display:block;float:left;width:250px;height:40px;line-height:30px;border:2px;border-style:solid; background:#A9A9A9; :border-color='color'" @click="optSchedule('休息')">休息</span>-->

          <span  style="display:block;float:left;width:250px;height:40px;line-height:30px;border:2px ;border-style:solid ;background:#FFFFFF ;margin-top: 25px" @click="optSchedule('清空')">清空</span>

      </el-row>
      <el-row style="margin-top: 15px" v-for="(item,index) in cycleScheduleList ">
        <span  style="display:block;float:left;width:300px;height:40px;line-height:30px;border:2px;border-style:solid;background:#32CD32;margin-top: 25px"@click="optSchedule(item.name)">{{item.name}}</span>

    </el-row>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="optScheduleOk">确 定</el-button>
        <el-button @click="cancelSchedule">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 排班详情对话框 -->
    <el-dialog :title="title" :visible.sync="openView" width="880px" append-to-body>
      <el-form ref="formView" :model="formView"   label-width="80px">
        <span style="font-weight:bold">基本信息</span>
        <el-divider></el-divider>
        <el-row>
          <el-col :span="12">
            <el-form-item label="排班名称" >
              <el-input v-model="formView.name" placeholder=""  disabled style="width: 180px"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="考勤组"  >
              <el-select
                v-model="formView.groupId"
                placeholder="考勤组"
                clearable
                size="small"
                style="width: 240px"
                disabled
              >
                <el-option
                  v-for="dict in groupOptions"
                  :key="dict.roleId"
                  :label="dict.roleName"
                  :value="dict.roleId"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>

          <el-col :span="12">
            <el-form-item label="状态"  disabled>
              <el-select
                v-model="formView.status"
                placeholder="状态"
                clearable
                size="small"
                style="width: 240px"
                disabled

              >
                <el-option
                  v-for="dict in statusOptions"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <span>
         <span style="font-weight:bold">排班信息</span>

        </span>

        <el-divider></el-divider>

        <span>
         班次说明：
          <el-row style="margin-top: 15px" v-for="(item,index) in termTimeShifList ">

          <span   style="display:block;float:left;width:400px;height:40px;line-height:30px; border:2px;border-style:solid;background:#32CD32">{{item.showDateTime}}</span>

        </el-row>
        <el-row style="margin-top: 15px" >
<!--          <el-col :span="2">-->
<!--            <span width="12px" style="display:block;float:left;width:120px;height:40px;line-height:30px;border:2px;border-style:solid; background:#A9A9A9; ">休息</span>-->
<!--          </el-col>-->
          <el-col :span="2">
            <span width="120px" style="display:block;float:left;width:120px;height:40px;line-height:30px;border:2px ;border-style:solid ;background:#FFFFFF ;">清空</span>
          </el-col>
        </el-row>
       </span>

        <span>
         周期说明：
          <el-row style="margin-top: 15px" v-for="(item,index) in cycleScheduleList ">
          <el-col :span="12">
          <span width="60px" style="display:block;float:left;width:100px;height:40px;line-height:30px;border:2px;border-style:solid;background:#32CD32">{{item.name}}</span>
          </el-col>
        </el-row>
       </span>
        <el-row>
          <el-form-item label="排班时间" name="scheduleDate" >
            <el-date-picker
              v-model="scheduleDateRange"
              size="small"
              style="width: 240px"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @change="changeDate"
              disabled
            ></el-date-picker>
          </el-form-item>
        </el-row>

        <el-row>
          使用方法：
        </el-row>
        <el-row>
          1、在人员的排班区域点击色块可以进行相应班次的填充，支持设置好排班周期后按周期填充。
        </el-row>
        <el-row>
          2、最大支持一次性按30天排班。
        </el-row>

        <el-divider></el-divider>
        <el-row>
          <el-col :span="9">
            <el-form-item label="岗位" prop="postName">
              <el-input
                v-model="queryInParams.postName"
                placeholder="请输入岗位"
                clearable
                size="small"
                style="width: 180px"

              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="用户名称" prop="userName">
              <el-input
                v-model="queryInParams.userName"
                placeholder="请输入用户名称"
                clearable
                size="small"
                style="width: 180px"
              />
            </el-form-item>


          </el-col>
          <el-col :span="6">
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleViewTableQuery">搜索</el-button>

            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10" class="mb8">

        </el-row>
        <el-table
          :data="tableData"
          border
          v-loading="userloading"
          style="width: auto"

        >

          <el-table-column
            prop="userName"
            label="姓名"
            width="100px"
            fixed
          >
            <template slot-scope="scope">
            <span
              :style="{ color: (scope.row.userId == userId  || (scope.row.postId == postId && scope.row.postId !=''))  ? 'red' : '' }"
            >
              {{ scope.row.userName }}</span
            >
            </template>
          </el-table-column>
          <el-table-column
            prop="idCard"
            label="身份证"
            width="180px"
            fixed

          >
            <template slot-scope="scope">
            <span
              :style="{ color: (scope.row.userId == userId  || (scope.row.postId == postId && scope.row.postId !=''))  ? 'red' : '' }"
            >
              {{ scope.row.idCard }}</span
            >
            </template>
          </el-table-column>
          <el-table-column
            prop="postName"
            label="岗位"
            width="100px"
            fixed
          >
            <template slot-scope="scope">
            <span
              :style="{ color: (scope.row.userId == userId  || (scope.row.postId == postId && scope.row.postId !=''))  ? 'red' : '' }"
            >
              {{ scope.row.postName }}</span
            >
            </template>

          </el-table-column>
          <template v-for="(item,index)  in tableTitleData">
            <el-table-column
              :prop="item.value"
              :label="item.lable"
              width="90px"
            >
            </el-table-column>
            <template slot-scope="scope">
            <span
              :style="{ color: (scope.row.userId == userId  || (scope.row.postId == postId && scope.row.postId !=''))  ? 'red' : '' }"
            >
              {{ scope.row[item.value]}}</span
            >
            </template>
            <template slot-scope="scope">
            <span
              :style="{ color: (scope.row.userId == userId  || (scope.row.postId == postId && scope.row.postId !=''))  ? 'red' : '' }"
            >
              {{ scope.row[item.value]}}</span
            >
            </template>
          </template>

        </el-table>

      </el-form>

    </el-dialog>


    <el-dialog title="选择填充班次" :visible.sync="openSchedule" width="480px" append-to-body>

      <el-row>
        <el-tag type="info" :color="color1" @click="changTag(1)">单次填充</el-tag>
        <el-tag type="info" :color="color2" @click="changTag(2)">周期填充</el-tag>

      </el-row>
      <el-divider></el-divider>

      <el-row style="margin-top: 15px" >

<!--        <span   :style="{'cursor':'pointer','display':'block', 'float':'left', 'width':'250px', 'height':'40px','line-height':'30px','border':'2px' ,'border-style':'solid' ,'margin-top': '25px',background:colorxx,'border-color':colorParams.xx}" s  @click="optSchedule(-1,'休息')">休息</span>-->

        <span  :style="{'cursor':'pointer','display':'block', 'float':'left', 'width':'250px', 'height':'40px','line-height':'30px','border':'2px' ,'border-style':'solid' ,'background':colorqk,'margin-top': '25px','border-color':colorParams.qk}" @click="optSchedule(-1,'清空')">清空</span>

      </el-row>
      <el-row style="margin-top: 15px" v-for="(item,index) in cycleScheduleList ">
        <span  :style="{'cursor':'pointer','display':'block', 'float':'left', 'width':'250px', 'height':'40px','line-height':'30px','border':'2px' ,'border-style':'solid' ,background:colorbc ,'margin-top': '25px','border-color':schedulColor[index]}" @click="optSchedule(index,item.name)">{{item.name}}</span>

      </el-row>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="optScheduleOk">确 定</el-button>
        <el-button @click="cancelSchedule">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="周期排班" :visible.sync="openCycle" width="540px" append-to-body>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="saveCycleSchedule"
          >保存
          </el-button>
        </el-col>
      </el-row>
      <el-table
        :data="tableCycleData"
        border
        @cell-dblclick="cellDblClick"
        v-loading="userloading"
        style="width: auto"
      >

        <el-table-column
          prop="name"
          label="班次名称"
          width="100px"
        >
        </el-table-column>

        <el-table-column
          prop="showDateTime"
          label="上下班时间"
          width="310px"
        >
        </el-table-column>
        <el-table-column
          prop="sort"
          label="排序"
          width="80px"
        >
          <template slot-scope="scope">
                <span v-if="!scope.row.isEditCell" style="cursor:pointer">{{scope.row.sort}}
                </span>
            <el-input v-if="scope.row.isEditCell"
                      v-model="scope.row.sort" placeholder="排序值"
                      @blur="cellBlur(scope.row,scope.column)"
                      style="width:70%" ref="hitchRef"></el-input>
            <!-- <el-button v-if="scope.row.isEditCell" type="success" icon="el-icon-check" size="mini" @click="submitName(scope.row)"></el-button> -->
          </template>


        </el-table-column>


      </el-table>

    </el-dialog>
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :on-change="beforeUpload"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件</span>
        </div>

      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>

</template>
<style>
.el-table .warning-row {
  background: oldlace;
}

</style>

<script>

import {getAllWeak} from  '@/utils/DateUtils'
import { getToken } from "@/utils/auth";
import {
  listTermSchedule,
  listTermTimeShift,
  listCycleSchedule,
  listRole,
  listUserSchedule,
  importSchedule,
  add,
  addCycleSchedule,
  getTermSchedule,
  delTermSchedule,
  update,
  editStatus
} from '@/api/job/termSchedule/termSchedule'

export default {
  name: "termSchedule",
  directives: {
    focus: {
      // 指令的定义
      inserted: function (el) {
        el.getElementsByTagName('input')[0].focus()

      }
    }
  },

  data() {
    return {
      show: false,
       type:1,
      disabledValue:true,
      fileList:[],
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "工具类导入",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/workJobApi/termSchedule/importSchedule",
        rowId:""
      },
      color1:'#000000',
      color2:'',
      colorxx:'#A9A9A9',
      colorqk:'#FFFFFF',
      colorbc:'#32CD32',
      schedulName:'',
      schedulColor:[],
      showEdit: [],
      needNumber: 0,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      ids: [],
      statusArray:[],
      flag: false,
      loading: true,
      userloading:false,
      isEdit:false,
      // 总条数
      total: 0,
      pageNum: 1,
      pageSize: 10,
      // 显示搜索条件
      showSearch: true,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // // 是否显示弹出层
      openSchedule: false,
      // 是否显示弹出层
      openView: false,
      // 是否显示弹出层
      openCycle:false,
      // 导出遮罩层
      exportLoading: false,
      // 日期范围
      dateRange: [],
      scheduleDateRange:[],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        createBy: undefined,
        status: undefined
      },
     colorParams: {
       xx:'',
       qk:'',
      },
      rowIndex:'',
      columnIndex:'',
      tableData:[],

      resultData:'',
      tableTitleData:[],
      userId:'',
      postId:'',
      groupOptions:[],
      queryInParams: {
      },
      // 表单参数
      form: {},
      formView: {},
      termTimeShifList: [],
      tableCycleData:[],
      termScheduleList: [],
      cycleScheduleList:[],
      statusOptions: [{value: 0, label: '启用'}, {value: 1, label: '停用'}],
      rules: {
        name: [
          { required: true, message: "排班名称不能为空", trigger: "blur" },
          { min: 2, max: 20, message: '排班名称长度必须介于 2 和 20 之间', trigger: 'blur' }
        ],
        status: [
          { required: true, message: "状态不能空"}
        ],
        groupId: [
          { required: true,  message: "考勤组不能为空", trigger: "blur" }
        ],
        scheduleDate: [
          { required: true, message: "排班时间不能为空", trigger: "blur"  }
        ],

      }
    }
  },
  created() {
    this.getList();
  },



  methods: {

    // 双击编辑
    cellDblClick(row,column) {

      if (column.property == "sort" ) {
        this.$set(row, "isEditCell", true);
      }


    },
    // 可以编辑框失去焦点
    cellBlur(row, column) {
      row.isEditCell= false;
      this.$set(row, 'isEditCell', false);
      for(var i =0;i<this.tableCycleData.length;i++){
        var name =this.tableCycleData.name;
         if(name==row.name){
           this.tableCycleData.sort =row.sort;
         }
      }

    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.statusArray = selection.map(item => item.status)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    cancelSchedule(){
      this.openSchedule = false;
      this.type=1;
      this.color1="#000000";
      this.color2="";
      this.colorParams.xx="";
      this.colorParams.qk="";
      for(var i=0;i<this.schedulColor.length;i++){
        this. schedulColor[i]='';

      }
    },

// 表单重置
    reset() {
      this.form = {
        id: undefined,
        name: undefined,
        dateTime: undefined,
        status: undefined,
        userName:undefined,
        postName:undefined,
      };
      this.queryInParams = {
        id :undefined,
        userName:undefined,
        postName:undefined,
      };
      this.scheduleDateRange=[];
      this.userId ='';
      this.postId ='';
      this.tableData=[];
      this.tableTitleData=[];
      this.resultData='';
      this.resetForm("form");
    },
    /** 查询列表 */
    getList() {
      this.loading = true;

      listTermSchedule(this.addDateRange(this.queryParams, this.dateRange)).then(
        response => {
          this.termScheduleList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    handleStatusChange(row) {
      let text = row.status == "0" ? "启用" : "停用";

      this.$confirm('确认要' + text +  row.name + '"班次吗?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        let data ={id:row.id,status:row.status};
        return editStatus(data);
      }).then(() => {
        this.msgSuccess(text + "成功");
      }).catch(function () {
        row.status = row.status === "0" ? "1" : "0";
      });
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
   //排班人员信息搜索
    handleTableQuery(){
      if(this.scheduleDateRange.length<1){
        this.$alert("排班时间是必须填写的", "错误提示", {dangerouslyUseHTMLString: true});
        return;
      }
      if(this.form.groupId ==null || this.form.groupId==''){
        this.$alert("考勤组是必须填写的", "错误提示", {dangerouslyUseHTMLString: true});
        return;
      }
      this.userId ='';
      this.postId ='';

      if((this.queryInParams.userName !="" && this.queryInParams.userName !=undefined)
        || (this.queryInParams.postName !="" && this.queryInParams.postName !=undefined)){
        var flag =0;
        for(var i=0;i<this.tableData.length;i++){
          let data =this.tableData[i];
          if(data.userName ==this.queryInParams.userName ){
            this.userId =data.userId;
            flag =1;
            return
          }
          if(data.postName ==this.queryInParams.postName ){
            this.postId =data.postId;
            flag =1;
            return
          }

        }
      if(flag ==0){
        this.$alert("没有搜索到信息，请核对", "错误提示", {dangerouslyUseHTMLString: true});

        return
      }


      }
      this.userId ='';
      this.postId ='';

      this.userloading = true;

      if (this.form.id == null || this.form.id==undefined) {
        this.queryInParams.id='';
        this.queryInParams.groupId=this.form.groupId;
        this.queryInParams.beginTime=this.scheduleDateRange[0];
        this.queryInParams.endTime=this.scheduleDateRange[1];

      }else{
        this.queryInParams.id=this.form.id;
        this.queryInParams.groupId=this.form.groupId;
        this.queryInParams.beginTime=this.scheduleDateRange[0];
        this.queryInParams.endTime=this.scheduleDateRange[1];
      }
      listUserSchedule(this.queryInParams).then(
        response => {

          this.tableData = response.rows;
          this.userloading = false;
        }
      );


    },

    handleViewTableQuery(){
      if(this.scheduleDateRange.length<1){
        this.$alert("排班时间是必须填写的", "错误提示", {dangerouslyUseHTMLString: true});
        return;
      }
      if(this.formView.groupId ==null || this.formView.groupId==''){
        this.$alert("考勤组是必须填写的", "错误提示", {dangerouslyUseHTMLString: true});
        return;
      }
      this.userId ='';
      this.postId ='';

      if((this.queryInParams.userName !="" && this.queryInParams.userName !=undefined)
        || (this.queryInParams.postName !="" && this.queryInParams.postName !=undefined)){
        var flag =0;
        for(var i=0;i<this.tableData.length;i++){
          let data =this.tableData[i];
          if(data.userName ==this.queryInParams.userName ){
            this.userId =data.userId;
            flag =1;
            return
          }
          if(data.postName ==this.queryInParams.postName ){
            this.postId =data.postId;
            flag =1;
            return
          }

        }
        if(flag ==0){
          this.$alert("没有搜索到信息，请核对", "错误提示", {dangerouslyUseHTMLString: true});

          return
        }


      }
      this.userId ='';
      this.postId ='';

      this.userloading = true;

        this.queryInParams.id=this.formView.id;
        this.queryInParams.groupId=this.formView.groupId;
        this.queryInParams.beginTime=this.scheduleDateRange[0];
        this.queryInParams.endTime=this.scheduleDateRange[1];

      listUserSchedule(this.queryInParams).then(
        response => {
          this.tableData = response.rows;
          this.userloading = false;
        }
      );


    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },

    resetTable(){

      this.userloading = true;

      if (this.form.id == null) {
        this.queryInParams.groupId=this.form.groupId;
        this.queryInParams.beginTime=this.scheduleDateRange[0];
        this.queryInParams.endTime=this.scheduleDateRange[1];

      }else{
        this.queryInParams.id=this.form.id;
        this.queryInParams.groupId=this.form.groupId;
        this.queryInParams.beginTime=this.scheduleDateRange[0];
        this.queryInParams.endTime=this.scheduleDateRange[1];
      }
      listUserSchedule(this.queryInParams).then(
        response => {
          this.tableData = response.rows;
          this.userloading = false;
        }
      );

    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id || this.ids;
      const status =row.status || this.statusArray;
      if(id=='' ){
        this.$alert("请先选中记录后再删除！", "错误提示", {dangerouslyUseHTMLString: true});
        return;
      }
      if(this.statusArray.length >0){
        for(var i =0;i<status.length;i++){
          if(status[i]==0){
            this.$alert("有启用状态不能删除！", "错误提示", {dangerouslyUseHTMLString: true});
            return;
          }
        }

      }else if(row.status ==0){
        this.$alert("有启用状态不能删除！", "错误提示", {dangerouslyUseHTMLString: true});
        return;
      }
      this.$confirm('是否确认删除编号为"' + id + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return delTermSchedule(id);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 提交按钮 */
    submitForm: function () {

      this.$refs["form"].validate(valid => {
        if (valid) {
          this.resultData='';
          for(var i=0;i<this.tableData.length;i++){
            this.resultData= this.resultData+this.tableData[i].userId;
            this.resultData = this.resultData+","+this.tableData[i].userName;
            this.resultData= this.resultData+","+this.tableData[i].postId;
            this.resultData= this.resultData+","+this.tableData[i].postName;
            this.resultData= this.resultData+","+this.tableData[i].idCard;
            for(var k=0;k<this.tableTitleData.length;k++){
              if(this.tableData[i][this.tableTitleData[k].lable]==null || this.tableData[i][this.tableTitleData[k].lable]==''){
                this.$alert("用户："+this.tableData[i].userName+"在日期："+this.tableTitleData[k].lable+"内没有排班，请核对", "错误提示", {dangerouslyUseHTMLString: true});
                return;
              }
              this.resultData= this.resultData+","+this.tableData[i][this.tableTitleData[k].lable];

            }
            if(i<this.tableData.length-1){

              this.resultData= this.resultData+";";
            }
          }

          this.form.tableData= this.resultData;
          this.form.beginTime=this.scheduleDateRange[0];
          this.form.endTime=this.scheduleDateRange[1];

          if (this.form.id != undefined) {
            update(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.resultData='';
              this.tableData=[];
              this.tableTitleData=[];
              this.getList();
            });
          } else {
            add(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.resultData='';
              this.tableData=[];
              this.tableTitleData=[];
              this.getList();
            });
          }
        }
      });
    },
    handleAdd() {
      this.listRole();
      this.listTermTimeShift();
      this.listCycleSchedule();
      this.reset();
      this.open = true;
      this.title = "添加信息";
      this.disabledValue=false;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.$confirm('编辑排班记录后需要重新导入考勤机记录，请知晓！', "提醒", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
       return true;
      }).then(() => {

        this.reset();
        this.disabledValue=true;
        const id = row.id;

        this.listRole();
        this.listTermTimeShift();
        this.listCycleSchedule();

        getTermSchedule(id).then(response => {
          this.form = response.data;

          this.scheduleDateRange.push(response.data.beginTime);
          this.scheduleDateRange.push(response.data.endTime);
          this.tableData=response.data.tableDataList;

          this.tableTitleData=response.data.tableTitleDataList;

          this.changTag(this.form.type);
          this.open = true;
          this.title = "排班编辑信息";
        });
      }).catch(() => {
      });

    },

    handleView(row) {
      this.userId ='';
      this.postId ='';
      this.reset();
      const id = row.id;
      this.listRole();
      this.listTermTimeShift();
      this.listCycleSchedule();
      getTermSchedule(id).then(response => {
        this.formView = response.data;
        this.scheduleDateRange.push(response.data.beginTime);
        this.scheduleDateRange.push(response.data.endTime);
        this.tableData=response.data.tableDataList;
        this.tableTitleData=response.data.tableTitleDataList;
        this.openView = true;
        this.title = "排班详情信息";
      });
    },
    handleExport(){
      const id =  this.ids;

      if(id.length  >1){
        this.$alert("抱歉，只能选择一条记录导出排班信息", "错误提示", {dangerouslyUseHTMLString: true});
        return;
      }

      if(id.length  <1){
        this.$alert("抱歉，请选择一条记录导出排班信息", "错误提示", {dangerouslyUseHTMLString: true});
        return;
      }
      let url =process.env.VUE_APP_BASE_API +'/workJobApi/termSchedule/userScheduleExport?id='+encodeURI(id);
       window.open( url);


    },


    listTermTimeShift(){
      listTermTimeShift().then(
        response => {
        this.termTimeShifList = response.rows;

         }
       );
    },
    //查询周期排班列表
    listCycleSchedule(){
      listCycleSchedule().then(
        response => {
          this.tableCycleData = response.rows;
          for(var i=0;i<this.tableCycleData.length;i++){

              this. schedulColor[i]='';

            }
          this.cycleScheduleList = response.rows;

        }
      );
    },
    //获取考勤组列表
    listRole(){
      listRole().then(
        response => {
          this.groupOptions = response.rows;
        }
      );
    },
    //修改排班日期
    changeDate() {
      let dateArray = this.scheduleDateRange;
        getAllWeak(dateArray[0],dateArray[1]);

       let showDate =   getAllWeak(dateArray[0],dateArray[1]);
       this.tableTitleData=[];
      this.tableData=[];
      for(var i =0;i<showDate.length;i++){
        let dateData={value:showDate[i],lable:showDate[i]};
        this.tableTitleData.push(dateData);
      }
    },
    //点击单元格触发
    cellClick(row, column, cell, event){
      if(column.index !=0 && column.index!=1){
        this.rowIndex=row.index;
        this.columnIndex=column.index;
        this.openSchedule=true;
      }


    },
   //切换周期填充合单次填充
    changTag(value){
      if(value==1){
        this.color1="#000000";
        this.color2="";
        this.type=1;
      }else  if(value==2){
        this.color1="";
        this.color2="#000000";
        this.type=2;
      }
    },
    //单元格操作
    optSchedule(index,value){
      if(this.type ==2){
        this.$alert("周期填充无需点击，请点确定按钮", "错误提示", {dangerouslyUseHTMLString: true});
        return;
      }
      if(this.type ==1){

        this.schedulName=value;
                this.colorParams.xx="";
        this.colorParams.qk="";
        for(var i=0;i<this.schedulColor.length;i++){
          this. schedulColor[i]='';

        }

        }
       if(value=='清空'){
          this.colorParams.qk="#DC143C";
        }else if(index !=-1){
          this.schedulColor[index]='#DC143C';
          this.$forceUpdate();
      }

    },

    //打开周期设置弹框
    openCycleConfig(){
      this.openCycle=true;
      this.listCycleSchedule();

    },
   //周期填充的确定操作
    optScheduleOk(){
    if(this.type==2){
      //周期填充
      for(var i=0;i<this.tableData.length;i++){
        var t =0;

        for(var k=0;k<this.tableTitleData.length;k++){
          this.tableData[i][this.tableTitleData[k].lable]=this.cycleScheduleList[t].name;
          if(t==this.cycleScheduleList.length-1){
            t=0;
          }else{
            t++;
          }

        }

      }

    }else {
      if(this.schedulName=='清空'){
        this.tableData[this.rowIndex][this.tableTitleData[this.columnIndex-3].lable]='';

      }else{

        this.tableData[this.rowIndex][this.tableTitleData[this.columnIndex-3].lable]=this.schedulName;

      }
    }
      this.cancelSchedule();

    },


    tableCellClassName({row, column, rowIndex, columnIndex}) {
      //注意这里是解构
      //利用单元格的 className 的回调方法，给行列索引赋值
      row.index = rowIndex;
      column.index = columnIndex;
    },
    //保存周期设置
    saveCycleSchedule(){
      addCycleSchedule(this.tableCycleData).then(response => {
        this.msgSuccess("保存周期排班设置成功");
        this.openCycle = false;
        this.listTermTimeShift();

      });
    },


    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;

    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {

      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", {dangerouslyUseHTMLString: true});

    },
    beforeUpload(file,fileList) {
      this.fileList=fileList;
    },

    // 提交上传文件
    submitFileForm() {
      let dateTime=this.scheduleDateRange[0]+"&"+this.scheduleDateRange[1]+"&"+this.form.groupId;
      this.upload.url="/workJobApi/termSchedule/importSchedule/"+dateTime;
      importSchedule(this.upload.url,this.fileList).then(res => {
        this.tableData = res.data;
        this.upload.open = false;
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();

      });

    },
    /** 导入按钮操作 */
    handleImport() {
      if(this.scheduleDateRange.length<1){
        this.$alert("排班时间是必须填写的", "错误提示", {dangerouslyUseHTMLString: true});
        return;
      }
      if(this.form.groupId ==null || this.form.groupId==''){
        this.$alert("考勤组是必须填写的", "错误提示", {dangerouslyUseHTMLString: true});
        return;
      }
      this.upload.title = "导入排班信息";
      this.upload.open = true;

    },
    /** 下载模板操作 */
    handleTamplantExport() {
      var fileName ="kqpbmb.xlsx";
      window.location.href = process.env.VUE_APP_BASE_API + "/common/download?fileName=" + encodeURI(fileName) + "&delete=" + false;
    },
  }
}
</script>

<style scoped>

</style>
